package com.yzt.zhuju.widget.widget;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.vectordrawable.graphics.drawable.Animatable2Compat;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions;
import com.bumptech.glide.load.resource.gif.GifDrawable;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.target.Target;
import com.bumptech.glide.request.transition.DrawableCrossFadeFactory;
import com.bumptech.glide.request.transition.Transition;

/**
 * User: fish
 * E-mail: 709913163@qq.com
 * Date: 2022/12/5
 * Time: 16:04
 * describe:
 */
public class ImageLoadManger {

    /**
     * 判断Activity是否Destroy
     */
    public static boolean isDestroy(Context mActivity) {
        if (mActivity == null) {
            return true;
        }
        if (mActivity instanceof Activity) {
            return ((Activity) mActivity).isFinishing() || ((Activity) mActivity).isDestroyed();
        }
        return false;
    }

    /**
     * 图片加载
     *
     * @param url       路径
     * @param iv        显示控件
     * @param defaultIv 默认图片
     */
    @SuppressLint("CheckResult")
    public static void loadIv(Context mContext, String url, ImageView iv, int defaultIv, int with, int height) {

        if (isDestroy(mContext)) {
            return;
        }

        if (iv == null) {
            return;
        }

        if (TextUtils.isEmpty(url)) {
            url = "https://";
        }

        if (url.startsWith("http://")) {
            url = url.replace("http://", "https://");
        }

        RequestOptions requestOptions = new RequestOptions();

        if (defaultIv > 0) {
            requestOptions.placeholder(defaultIv);
            requestOptions.error(defaultIv);
        }

        DrawableCrossFadeFactory drawableCrossFadeFactory = new DrawableCrossFadeFactory.Builder(700).setCrossFadeEnabled(true).build();
        iv.setBackgroundColor(Color.TRANSPARENT);
        requestOptions.override(with, height).diskCacheStrategy(DiskCacheStrategy.ALL);

        Glide.with(mContext)
                .load(url)
                .disallowHardwareConfig()
                .apply(requestOptions)
                .transition(DrawableTransitionOptions.withCrossFade(drawableCrossFadeFactory))
                .into(iv);
    }

    /**
     * 图片加载
     *
     * @param url       路径
     * @param iv        显示控件
     * @param defaultIv 默认图片
     */
    @SuppressLint("CheckResult")
    public static void loadIv(Context mContext, String url, ImageView iv, int defaultIv, RequestOptions bitmapTransform) {

        if (isDestroy(mContext)) return;

        if (iv == null) return;

        if (TextUtils.isEmpty(url)) {
            url = "https://";
        }

        if (url.startsWith("http://")) {
            url = url.replace("http://", "https://");
        }

        if (bitmapTransform == null) {
            bitmapTransform = new RequestOptions();
        }

        if (defaultIv > 0) {
            bitmapTransform.placeholder(defaultIv);
            bitmapTransform.error(defaultIv);
        }

        DrawableCrossFadeFactory drawableCrossFadeFactory = new DrawableCrossFadeFactory.Builder(700).setCrossFadeEnabled(true).build();
        iv.setBackgroundColor(Color.TRANSPARENT);
        bitmapTransform.diskCacheStrategy(DiskCacheStrategy.ALL);

        Glide.with(mContext)
                .load(url)
                .disallowHardwareConfig()
                .apply(bitmapTransform)
                .transition(DrawableTransitionOptions.withCrossFade(drawableCrossFadeFactory))
                .into(iv);
    }

    /**
     * 加载本地资源文件
     */
    public static void loadIv(Context mContext, int id, ImageView iv) {
        if (isDestroy(mContext)) return;
        if (iv == null) return;
        RequestOptions requestOptions = new RequestOptions();
        DrawableCrossFadeFactory drawableCrossFadeFactory = new DrawableCrossFadeFactory.Builder(700).setCrossFadeEnabled(true).build();
        iv.setBackgroundColor(Color.TRANSPARENT);
        Glide.with(mContext)
                .load(id)
                .disallowHardwareConfig()
                .apply(requestOptions)
                .transition(DrawableTransitionOptions.withCrossFade(drawableCrossFadeFactory))
                .into(iv);
    }

    /**
     * 图片加载
     *
     * @param url       路径
     * @param iv        显示控件
     * @param defaultIv 默认图片
     */
    public static void loadIv(Context mContext, String url, ImageView iv, int defaultIv) {
        Glide.with(mContext)
                .load(url)
                .disallowHardwareConfig()
                .placeholder(defaultIv)
                .error(defaultIv)
                .into(iv);
    }

    /**
     * 图片加载
     *
     * @param url 路径
     * @param iv  显示控件
     */
    public static void loadIv(Context mContext, String url, ImageView iv) {
        Glide.with(mContext)
                .load(url)
                .disallowHardwareConfig()
                .into(iv);
    }

    /**
     * 加载动画一次
     */
    public static void loadGifIvForever(Context mContext, String url, ImageView iv, OnPlayGifListener onPlayGifListener) {
        if (isDestroy(mContext)) return;
        if (iv == null) return;
        Glide.with(mContext).load(url)
                .listener(new RequestListener<Drawable>() {
                    @Override
                    public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                        if (onPlayGifListener != null) {
                            onPlayGifListener.onPlayEnd();
                        }
                        return false;
                    }

                    @Override
                    public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
                        try {
                            GifDrawable drawable = (GifDrawable) resource;
                            //只播放一次
                            drawable.setLoopCount(-1);
                            drawable.registerAnimationCallback(new Animatable2Compat.AnimationCallback() {
                                @Override
                                public void onAnimationStart(Drawable drawable) {
                                    super.onAnimationStart(drawable);
                                    if (onPlayGifListener != null) {
                                        onPlayGifListener.onPlayStart();
                                    }
                                }

                                @Override
                                public void onAnimationEnd(Drawable drawable) {
                                    super.onAnimationEnd(drawable);
                                    if (onPlayGifListener != null) {
                                        onPlayGifListener.onPlayEnd();
                                    }
                                }
                            });
                        } catch (ClassCastException e) {
                            e.printStackTrace();
                            if (onPlayGifListener != null) {
                                onPlayGifListener.onPlayEnd();
                            }
                        }
                        return false;
                    }
                }).into(iv);
    }

    /**
     * 加载动画一次
     */
    public static void loadGifIvOnce(Context mContext, String url, ImageView iv, OnPlayGifListener onPlayGifListener) {
        if (isDestroy(mContext)) return;
        if (iv == null) return;
        Glide.with(mContext).load(url)
                .listener(new RequestListener<Drawable>() {
                    @Override
                    public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                        if (onPlayGifListener != null) {
                            onPlayGifListener.onPlayEnd();
                        }
                        return false;
                    }

                    @Override
                    public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
                        try {
                            GifDrawable drawable = (GifDrawable) resource;
                            drawable.setLoopCount(1);//只播放一次
                            drawable.registerAnimationCallback(new Animatable2Compat.AnimationCallback() {
                                @Override
                                public void onAnimationStart(Drawable drawable) {
                                    super.onAnimationStart(drawable);
                                    if (onPlayGifListener != null) {
                                        onPlayGifListener.onPlayStart();
                                    }
                                }

                                @Override
                                public void onAnimationEnd(Drawable drawable) {
                                    super.onAnimationEnd(drawable);
                                    if (onPlayGifListener != null) {
                                        onPlayGifListener.onPlayEnd();
                                    }
                                }
                            });
                        } catch (ClassCastException e) {
                            e.printStackTrace();
                            if (onPlayGifListener != null) {
                                onPlayGifListener.onPlayEnd();
                            }
                        }
                        return false;
                    }
                }).into(iv);
    }

    public interface OnPlayGifListener {

        void onPlayStart();

        void onPlayEnd();
    }

    /**
     * 获取图片drawable
     */
    public static void load4Drawable(Context context, String url, ImageRequestListener listener) {
        load4Drawable(context, url, -1, -1, listener);
    }

    /**
     * 获取图片drawable
     */
    public static void load4Drawable(Context context, String url, int width, int height, ImageRequestListener listener) {
        if (isDestroy(context)) {
            return;
        }

        RequestOptions options = new RequestOptions().override(width, height);
        load4Drawable(context, url, options, listener);
    }

    private static void load4Drawable(Context context, String url, RequestOptions options, ImageRequestListener listener) {
        Glide.with(context).load(url)
                .apply(options)
                .into(new CustomTarget<Drawable>() {
                    @Override
                    public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
                        listener.onResourceReady(resource);
                    }

                    @Override
                    public void onLoadCleared(@Nullable Drawable placeholder) {

                    }

                    @Override
                    public void onLoadFailed(@Nullable Drawable errorDrawable) {
                        listener.onError();
                    }
                });
    }

    /**
     * 仅处理需要查看原图
     */
    public static void loadWebp(Context mContext, String url, ImageView iv, int withPX, int defaultIv) {
        if (isDestroy(mContext)) {
            return;
        }
        // url = url2webp(url, withPX);
        RequestOptions requestOptions = new RequestOptions();
        requestOptions.placeholder(defaultIv);
        requestOptions.error(defaultIv);
        iv.setBackgroundColor(Color.TRANSPARENT);
        requestOptions.override(-1, -1).diskCacheStrategy(DiskCacheStrategy.ALL).centerCrop();

        Glide.with(mContext).load(url).apply(requestOptions).into(iv);
    }

    public interface ImageRequestListener {

        void onResourceReady(@NonNull Drawable resource);

        void onError();
    }
}